package br.edu.ufcg.dsc.actions.search;

import java.util.List;

import org.apache.struts2.config.ParentPackage;
import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import org.apache.struts2.dispatcher.ServletDispatcherResult;

import br.edu.ufcg.dsc.domain.Resource;
import br.edu.ufcg.dsc.domain.ResourceType;
import br.edu.ufcg.dsc.services.ResourceService;

import com.opensymphony.xwork2.ActionChainResult;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;

@ParentPackage(value = "myPackage")
@Results(value={@Result(name = "success", type = ServletDispatcherResult.class, value = "/jsp/search/result.jsp"),
		@Result(name = "input", type = ActionChainResult.class, value = "indexSearchResource", params = {"namespace", "/"})})

public class BasicSearchAction extends ActionSupport {

	private static final long serialVersionUID = -7113103956151743558L;

	private String searchBy;
	
	private String type;
	
	private String query;
	
	private List<Resource> resourceResult;
	
	public List<Resource> getResourceResult() {
		return resourceResult;
	}

	public void setResourceResult(List<Resource> resourceResult) {
		this.resourceResult = resourceResult;
	}

	public void setSearchBy(String searchBy) {
		this.searchBy = searchBy;
	}
	
	public void setType(String type) {
		this.type = type;
	}
	
	@RequiredStringValidator(fieldName="query", trim=true, key="search.query.required", message = "Default Message")
	@StringLengthFieldValidator(fieldName="query", trim=true, minLength="2", key="search.query.minSize", message="Default Message")
	public String getQuery() {
		return query;
	}
	
	public void setQuery(String query) {
		this.query = query;
	}
	
	@Override
	public String execute() throws Exception {
		ResourceType typeResource = ResourceType.valueOf(type);
		if (searchBy.equalsIgnoreCase("AUTHOR"))
			resourceResult = ResourceService.findByAuthor(query, typeResource);
		else if (searchBy.equalsIgnoreCase("ISBN"))
			resourceResult = ResourceService.findByISBN(query, typeResource);
		else if (searchBy.equalsIgnoreCase("ISSN"))
			resourceResult = ResourceService.findByISSN(query, typeResource);
		else if (searchBy.equalsIgnoreCase("TITLE"))
			resourceResult = ResourceService.findByTitle(query, typeResource);
		return SUCCESS;
	}

}
